package com.xkcyy.one.ai.common.tool;

import com.fasterxml.jackson.databind.JsonNode;
import com.xkcyy.one.ai.llm.model.ToolDefinition;
import lombok.extern.slf4j.Slf4j;

/**
 * 内置工具实现
 * 
 * @author yuand
 */
@Slf4j
public class BuiltinTool extends AbstractTool {

    public BuiltinTool(ToolDefinition definition) {
        super(definition);
    }

    @Override
    protected String executeInternal(String inputParams) {
        try {
            JsonNode params = objectMapper.readTree(inputParams);
            String operation = params.get("operation").asText();

            switch (operation) {
                case "echo":
                    return params.get("message").asText();
                case "math":
                    return executeMathOperation(params);
                default:
                    throw new IllegalArgumentException("Unsupported operation: " + operation);
            }
        } catch (Exception e) {
            log.error("Error executing builtin tool", e);
            throw new RuntimeException("Failed to execute builtin tool", e);
        }
    }

    private String executeMathOperation(JsonNode params) {
        String op = params.get("op").asText();
        double a = params.get("a").asDouble();
        double b = params.get("b").asDouble();

        double result;
        switch (op) {
            case "add":
                result = a + b;
                break;
            case "subtract":
                result = a - b;
                break;
            case "multiply":
                result = a * b;
                break;
            case "divide":
                if (b == 0) {
                    throw new ArithmeticException("Division by zero");
                }
                result = a / b;
                break;
            default:
                throw new IllegalArgumentException("Unsupported math operation: " + op);
        }

        return String.valueOf(result);
    }

    @Override
    public String getType() {
        return "builtin";
    }
}